<template>
  <div>
    <div class="df jc-sb title-btn">
      <div> <el-input v-model="search_inp" @keydown.enter="search_click" placeholder="输入任意字段进行模糊查询" class="input-with-select">
          <template #append>
            <el-button @click="search_click" :icon="Search" />
          </template>
        </el-input>
      </div>
      <el-button type="primary" @click="bar_into">网吧开户</el-button>
    </div>
    <el-table border :data="tableData" style="width: 100%;margin-top: 15px;height: 640px;">
      <el-table-column prop="AgentUserName" label="上级代理" />.
      <el-table-column prop="BarName" label="网吧地址">
        <template #default="scope">
          <el-tooltip class="box-item" effect="dark" :content="scope.row.BarName" placement="top-start">
            <p class="ov1"> {{scope.row.BarName}}</p>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="OwnerUserName" label="用户名" />
      <el-table-column prop="OwnerUserPassword" label="密码" />
      <el-table-column prop="Balance" label="余额" />
      <el-table-column prop="OwnerPhone" label="手机号">
        <template #default="scope">
          <el-tooltip class="box-item" effect="dark" :content="scope.row.OwnerPhone" placement="top-start">
            <p class="ov1"> {{scope.row.OwnerPhone}}</p>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="OwnerMisc" label="MISC" />
      <!-- <el-table-column prop="OwnerNotice" label="网吧公告">
        <template #default="scope">
          <el-tooltip class="box-item" effect="dark" :content="scope.row.natical" placement="top-start">
            <p class="ov1"> {{scope.row.OwnerNotice}}</p> 
          </el-tooltip>
        </template> 
      </el-table-column> -->
      <el-table-column prop="OwnerStatus" label="网吧状态">
        <template #default="scope">
          <el-switch v-model="scope.row.status" class="ml-2" @change="switch_change(scope.row)" />

        </template>
      </el-table-column>
      <el-table-column prop="ownerUserMAC" label="MAC" width="150" />
      <el-table-column prop="IP" label="IP" />
      <el-table-column prop="" label="操作" width="200">
        <template #default="scope">
          <el-button @click="edit(scope.row)" size="small" type="primary" link>修改</el-button>
          <el-popconfirm title="不在考虑一下?" confirm-button-text="确定" cancel-button-text="取消" @confirm="del(scope.row)">
            <template #reference>
              <el-button size="small" type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>

    {{ nexttick_arr[1] }}

    <Pagination style="margin-top: 10px;" :total="total" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></Pagination>

    <el-dialog v-model="dialogVisible" title="提示" width="40%" draggable>
      <div style="padding-right: 30px;">
        <el-form ref="ruleFormRef" :rules="rules" :model="form" label-width="120px" class="demo-ruleForm" status-icon>
          <el-form-item label="代理名称" prop="AgentUserName">
            <!-- <el-input v-model="form.AgentUserName" /> -->
            <el-select v-model="form.AgentUserName" placeholder="请选择上级代理" style="width: 100%;">
              <el-option v-for="(item,index) in dailiList" :key="index" :label="item.filter_name" :value="item.AgentUserName" @click="select_change(item)" />
            </el-select>
          </el-form-item>
          <el-form-item label="网吧余额" prop="Balance">
            <el-input v-model="form.Balance" />
          </el-form-item>
          <el-form-item label="地址" prop="adress">
            <el-cascader :options="layArea.array" :props="{ value: 'address',label: 'address',children: 'children'}" v-model="form_adress" style="width: 100%;">
            </el-cascader>
          </el-form-item>

          <el-form-item label="网吧名称" prop="BarName">
            <el-input v-model="form.BarName" />
          </el-form-item>
          <el-form-item label="用户名" prop="OwnerUserName">
            <el-input v-model="form.OwnerUserName" :disabled="is_add_edit=='edit'" />
          </el-form-item>
          <el-form-item label="密码" prop="OwnerUserPassword">
            <el-input v-model="form.OwnerUserPassword" />
          </el-form-item>
          <el-form-item label="IP地址" prop="IP">
            <el-input v-model="form.IP" />
          </el-form-item>
          <el-form-item label="MISC" prop="OwnerMisc">
            <el-input v-model="form.OwnerMisc" />
          </el-form-item>
          <!-- <el-form-item label="公告" prop="OwnerNotice">
            <el-input v-model="form.OwnerNotice" />
          </el-form-item> -->
          <el-form-item label="手机号" prop="OwnerPhone">
            <el-input v-model="form.OwnerPhone" />
          </el-form-item>

          <el-form-item label="MAC" prop="ownerUserMAC">
            <el-input v-model="form.ownerUserMAC" />
          </el-form-item>

        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="enter_add">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>
  

<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import http from '../../http'
import { useCounterStore } from '../../current/index'
import { storeToRefs } from 'pinia'
import { layArea } from '../../utiles/area'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import Pagination from '../components/Pagination.vue'
import { gbktoutf8 } from '../../utiles/gbktoutf8'

const store = useCounterStore()
const { userInfo } = storeToRefs(store) //  数据
const { formart_sql } = store //方法

onMounted(async () => {
  // tableData.value = await get_list("SELECT * FROM owneruser", "userglobal");

  let total_arr = await get_total('SELECT COUNT(*) FROM owneruser', 'userglobal')
  total.value = Number(total_arr[0]['COUNT(*)'])

  tableData.value = await get_list(
    'SELECT * FROM owneruser ORDER BY owneruser.OwnerUserName LIMIT 15 OFFSET 0',
    'userglobal'
  )
})
const tableData = ref<any>([])
interface RuleForm {
  AgentUserName: string //上级代理
  Balance: string //余额
  BarName: string //网吧名称
  IP: string
  OwnerMisc: string
  OwnerNotice: string
  OwnerPhone: string //手机号
  OwnerStatus: string
  OwnerUserName: string
  OwnerUserPassword: string
  ownerUserMAC: string
}
const form = ref<RuleForm>({
  AgentUserName: '', //上级代理
  Balance: '0', //余额
  BarName: '', //网吧名称
  IP: '',
  OwnerMisc: '',
  OwnerNotice: '',
  OwnerPhone: '', //手机号
  OwnerStatus: '0',
  OwnerUserName: '',
  OwnerUserPassword: '',
  ownerUserMAC: ''
})
const form_adress = ref()
// 表单校验
const rules = reactive<FormRules<RuleForm>>({
  AgentUserName: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
    { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' }
  ],
  OwnerPhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { min: 11, max: 11, message: '请输入11位数的手机号', trigger: 'blur' }
  ],
  OwnerUserName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  OwnerUserPassword: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  adress: [{ required: true, message: '请选择地址', trigger: 'blur' }],
  BarName: [{ required: true, message: '请输入网吧名称', trigger: 'blur' }]
})

const dialogVisible = ref(false) //弹框

// 修改
const edit = (row) => {
  is_add_edit.value = 'edit'
  console.log(row)
  form_adress.value = row.BarName.split('|').slice(0, 3)
  console.log(form_adress.value)

  form.value = {
    AgentUserName: row.AgentUserName, //上级代理
    Balance: row.Balance, //余额
    BarName: row.BarName.split('|')[row.BarName.split('|').length - 1], //网吧名称
    IP: row.IP,
    OwnerMisc: row.OwnerMisc,
    // OwnerNotice: row.OwnerNotice,
    OwnerNotice: row.OwnerNotice,
     
    OwnerPhone: row.OwnerPhone, //手机号
    OwnerStatus: row.OwnerStatus,
    OwnerUserName: row.OwnerUserName,
    OwnerUserPassword: row.OwnerUserPassword,
    ownerUserMAC: row.ownerUserMAC
  }

  dialogVisible.value = true
  console.log(form.value)
}
// 删除
const del = async (row) => {
  // const res1 = await http.corsApi('/', 'post', {
  //   packID: '123456',
  //   packageType: 'adminSql',
  //   packageContent: {
  //     AgentUserName: userInfo.value.username,
  //     AgentUserPassword: userInfo.value.password,
  //     sql: ` UPDATE userglobal.cami SET Distributor = 'new_distributor' WHERE Distributor = '${row.OwnerUserName}';`,
  //     dbName: 'userglobal'
  //   }
  // })
  // if (res1.packageContent.packageStatus !== 0) {return false}

  const res = await http.corsApi('/', 'post', {
    packID: '123456',
    packageType: 'adminSql',
    packageContent: {
      AgentUserName: userInfo.value.username,
      AgentUserPassword: userInfo.value.password,
      sql: `DELETE FROM owneruser WHERE OwnerUserName = '${row.OwnerUserName}'`,
      dbName: 'userglobal'
    }
  })
  console.log(res)
  if (res.packageContent.packageStatus === 0) {
    ElMessage.success('删除成功')
    tableData.value = await get_list(
      'SELECT * FROM owneruser ORDER BY owneruser.OwnerUserName LIMIT 15 OFFSET 0',
      'userglobal'
    )
  } else {
    ElMessage.error('删除失败' + res.packageContent.packageMsg)
  }
}
// 网吧开户
const bar_into = () => {
  is_add_edit.value = 'add'
  dialogVisible.value = true
  form_adress.value = []
  form.value = {
    AgentUserName: '', //上级代理
    Balance: '0', //余额
    BarName: '', //网吧名称
    IP: '',
    OwnerMisc: '',
    OwnerNotice: '',
    OwnerPhone: '', //手机号
    OwnerStatus: '0',
    OwnerUserName: '',
    OwnerUserPassword: '',
    ownerUserMAC: ''
  }
  get_daili_list()
}
// 确认开户
const is_add_edit = ref('add')
const enter_add = async () => {
  if (
    form.value.OwnerPhone == '' ||
    form.value.AgentUserName == '' ||
    form_adress.value.length <= 0 ||
    form.value.BarName == '' ||
    form.value.OwnerUserName == '' ||
    form.value.OwnerUserPassword == ''
  ) {
    ElMessage.error('请检查必填项是否完整')
    return false
  }

  const res_select = await http.corsApi('/', 'post', {
    packID: '123456',
    packageType: 'adminSql',
    packageContent: {
      AgentUserName: userInfo.value.username,
      AgentUserPassword: userInfo.value.password,
      // sql: `SELECT * FROM owneruser WHERE OwnerUserName = '${form.value.OwnerUserName}'OR OwnerPhone = '${form.value.OwnerPhone}'`,
      sql: `SELECT * FROM owneruser WHERE OwnerUserName = '${form.value.OwnerUserName}'`,
      dbName: 'userglobal'
    }
  })
  if (res_select.packageContent.packageMsg != '成功' && is_add_edit.value == 'add') {
    ElMessage.error('用户名重复')
    return false
  }

  let bar_name = form.value.BarName
  form.value.BarName = form_adress.value.join('|') + '|' + bar_name
  const val_arr = filter_sql(form.value)
  console.log(val_arr)

  let sql = ''
  if (is_add_edit.value == 'add') {
    sql = `INSERT INTO owneruser (${val_arr.key_string}) VALUES(${val_arr.value_string})`
  } else {
    let val_sql = await formart_sql(form.value)
    sql = `UPDATE owneruser SET ${val_sql} WHERE OwnerUserName = '${form.value.OwnerUserName}'`
  }

  const res = await http.corsApi('/', 'post', {
    packID: '123456',
    packageType: 'adminSql',
    packageContent: {
      AgentUserName: userInfo.value.username,
      AgentUserPassword: userInfo.value.password,
      sql,
      dbName: 'userglobal'
    }
  })
  console.log(res)
  if (res.packageContent.packageStatus === 0) {
    if (is_add_edit.value == 'add') {
      ElMessage.success('开户成功')
    } else {
      ElMessage.success('修改成功')
    }

    dialogVisible.value = false
    // tableData.value = await get_list("SELECT * FROM owneruser", "userglobal");
    tableData.value = await get_list(
      'SELECT * FROM owneruser ORDER BY owneruser.OwnerUserName LIMIT 15 OFFSET 0',
      'userglobal'
    )
  } else {
    if (is_add_edit.value == 'add') {
      ElMessage.error('开户失败' + res.packageContent.packageMsg)
    } else {
      // ElMessage.error('修改失败' + res.packageContent.packageMsg)
    }
  }
}
const select_change = (item) => {
  console.log(item)
}

// 模糊查询
const search_inp = ref('')
const search_click = async () => {
  if (search_inp.value == '') {
    tableData.value = await get_list(
      'SELECT * FROM owneruser ORDER BY owneruser.OwnerUserName LIMIT 15 OFFSET 0',
      'userglobal'
    )
  } else
    tableData.value = await get_list(
      `SELECT * FROM owneruser WHERE OwnerUserName LIKE '%${search_inp.value}%' OR OwnerPhone LIKE  '%${search_inp.value}%' OR BarName LIKE  '%${search_inp.value}%' OR ownerUserMAC LIKE  '%${search_inp.value}%' OR Balance LIKE  '%${search_inp.value}%' OR IP LIKE  '%${search_inp.value}%'`,
      'userglobal'
    )
}

// 网吧状态
const switch_change = async (row) => {
  console.log(row)
  let status = row.status ? '0' : '1'
  const res = await http.corsApi('/', 'post', {
    packID: '123456',
    packageType: 'adminSql',
    packageContent: {
      AgentUserName: userInfo.value.username,
      AgentUserPassword: userInfo.value.password,
      sql: `UPDATE owneruser SET OwnerStatus = '${status}' WHERE OwnerUserName = '${row.OwnerUserName}'`,
      dbName: 'userglobal'
    }
  })
  console.log(res)

  if (res.packageContent.packageStatus === 0) {
    ElMessage.success('更新成功')
    dialogVisible.value = false
    // tableData.value = await get_list("SELECT * FROM owneruser", "userglobal");
    tableData.value = await get_list(
      'SELECT * FROM owneruser ORDER BY owneruser.OwnerUserName LIMIT 15 OFFSET 0',
      'userglobal'
    )
  } else {
    ElMessage.error('更新失败' + res.packageContent.packageMsg)
  }
}

// 代理列表
const dailiList = ref([])
const get_daili_list = async () => {
  const res = await get_list('SELECT * FROM agentuser', 'userglobal')

  for (const ele of res) {
    ele['filter_name'] = `${ele.AgentUserName}      ${
      ele.AgentLevel == 0
        ? '最高代理'
        : ele.AgentLevel == 1
        ? '一级代理'
        : ele.AgentLevel == 2
        ? '二级代理'
        : ele.AgentLevel == 3
        ? '三级代理'
        : ele.AgentLevel + '级代理'
    }`
  }
  console.log(res)
  dailiList.value = res
}

const nexttick_arr = ref([])
const get_list = async (sql, dbName) => {
  const res = await http.corsApi('/', 'post', {
    packID: '123456',
    packageType: 'adminSql',
    packageContent: {
      AgentUserName: userInfo.value.username,
      AgentUserPassword: userInfo.value.password,
      sql: sql,
      dbName: dbName
    }
  })
  console.log(res)
  let data = []
  if (res && res.packageContent.packageMsg == '成功') {
    data = []
  } else {
    data = JSON.parse(res.packageContent.packageMsg)
    let newarr = data.map(async (item) => {
      item['status'] = item.OwnerStatus == 0 ? true : false
      console.log(item.BarName)
      // item['natical'] = item.OwnerNotice ? await gbktoutf8(item.OwnerNotice) : ''

      // console.log(decodeURIComponent(escape(window.atob('1tjH7HzW2MfsytB8zfLW3cf4fM34sMk='))));

      // item.BarName = decodeURIComponent(escape(window.atob(item.BarName)))

      return item
    })

    // nextTick(async () => {
    //   for (var i = 0; i < data.length; i++) {
    //     data[i]['natical'] = data[i].OwnerNotice ? await gbktoutf8(data[i].OwnerNotice) : ''
    //   }
    //   nexttick_arr.value = data
    // })

  }

  console.log(data)

  return data
}

const page = ref(1) //页码数
const pageSize = ref(15) //每页条数
const total = ref(10)

// 分页
const handleSizeChange = async (val: number) => {
  console.log(`${val} items per page`)
  pageSize.value = val
  // page.value = 1
  // 每页显示的条数
  if ((page.value - 1) * pageSize.value - 1 <= 0) {
    tableData.value = await get_list(
      `SELECT * FROM owneruser ORDER BY owneruser.OwnerUserName LIMIT ${pageSize.value} OFFSET 0`,
      'userglobal'
    )
  } else {
    tableData.value = await get_list(
      `SELECT * FROM owneruser ORDER BY owneruser.OwnerUserName LIMIT ${pageSize.value} OFFSET ${
        (page.value - 1) * pageSize.value
      }`,
      'userglobal'
    )
  }
}
const handleCurrentChange = async (val: number) => {
  console.log(`current page: ${val}`)
  page.value = val
  // 当前页码数
  if ((val - 1) * pageSize.value - 1 <= 0) {
    tableData.value = await get_list(
      `SELECT * FROM owneruser ORDER BY owneruser.OwnerUserName LIMIT  ${pageSize.value} OFFSET 0`,
      'userglobal'
    )
  } else {
    tableData.value = await get_list(
      `SELECT * FROM owneruser ORDER BY owneruser.OwnerUserName LIMIT  ${pageSize.value} OFFSET ${
        (page.value - 1) * pageSize.value
      }`,
      'userglobal'
    )
  }
}

const get_total = async (sql, dbName) => {
  const res = await http.corsApi('/', 'post', {
    packID: '123456',
    packageType: 'adminSql',
    packageContent: {
      AgentUserName: userInfo.value.username,
      AgentUserPassword: userInfo.value.password,
      sql: sql,
      dbName: dbName
    }
  })
  console.log(res)
  return JSON.parse(res.packageContent.packageMsg)
}

// 拼接sql
const filter_sql = (data) => {
  let arr = Object.keys(data)
  let key_string = ''
  let value_string = ''
  for (var i = 0; i < arr.length; i++) {
    if (i == arr.length - 1) {
      key_string += arr[i] + ''

      if (data[arr[i]] == null) {
        value_string += `${data[arr[i]]}`
      } else {
        value_string += `'${data[arr[i]]}'`
      }
    } else {
      key_string += arr[i] + ','
      if (data[arr[i]] == null) {
        value_string += `${data[arr[i]]},`
      } else {
        value_string += `'${data[arr[i]]}',`
      }
    }
  }

  console.log(key_string)
  console.log(value_string)
  return {
    key_string,
    value_string
  }
}
</script>

<style scoped lang="scss">
</style>